package com.gitee.cui.basic.use;

import lombok.extern.slf4j.Slf4j;

/**
 * 演示线程的join
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/10 11:19
 **/
@Slf4j
public class Join {

    /**
     * 睡眠时长
     */
    public static final int SLEEP_GAP = 5000;
    /**
     * 睡眠次数
     */
    public static final int MAX_TURN = 5;

    static class SleepThread extends Thread {
        static int threadSeqNumber = 1;

        public SleepThread() {
            super("sleepThread-" + threadSeqNumber);
            threadSeqNumber++;
        }

        public void run() {
            try {
                for (int i = 1; i < MAX_TURN; i++) {
                    log.info(getName() + ", 睡眠轮次：{}", i);
                    // 线程睡眠一会
                    Thread.sleep(SLEEP_GAP);
                }
            } catch (InterruptedException e) {
                log.info(getName() + " 发生异常被中断.");
            }
            log.info(getName() + " 运行结束.");
        }
    }

    public static void main(String[] args) {
        SleepThread sleepThread = new SleepThread();
        log.info("启动sleepThread");
        sleepThread.start();
        try {
            // 合并线程，不限时，会使main线程处于TIME——WAITING状态
            sleepThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("启动线程sleepThread2");
        SleepThread sleepThread2 = new SleepThread();
        sleepThread2.start();
        try {
            // 合并线程，限时1秒
            sleepThread2.join(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("线程运行结束");
    }
}
